package edu.scau.cxq.gp.common.utils;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Data
@Component
public class FileUtils {

    /**
     * 保存文件
     * @param path
     * @param inputStream
     */
    public boolean saveFile(String path, InputStream inputStream) {

        OutputStream os = null;

        try {
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath());
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            return false;
        } catch (Exception e) {
            return false;
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return true;
    }

    /**
     * 将字符串List集合转成InputStream
     * @param content
     * @return
     * @throws UnsupportedEncodingException
     */
    public InputStream changeStringIntoInputStream(String content) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
    }


    /**
     * 读取文本文件 将文件内容转换成字符串
     * @param filepath
     * @return
     * @throws IOException
     */
    public String getTemplateContent(String filepath) throws IOException {
        File file = new File(filepath);
        if(!file.exists()){
            return null;
        }
        FileInputStream inputStream = new FileInputStream(file);
        int length = inputStream.available();
        byte[] bytes = new byte[length];
        inputStream.read(bytes);
        inputStream.close();
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * 获取文件夹下的所有文件路径（可设置子文件夹）
     * @param directoryPath
     * @param isAddDirectory
     * @return
     */
    public List<String> getAllFile(String directoryPath, boolean isAddDirectory) {
        List<String> list = new ArrayList<String>();
        File baseFile = new File(directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if(isAddDirectory){
                    list.add(file.getAbsolutePath());
                }
                list.addAll(getAllFile(file.getAbsolutePath(),isAddDirectory));
            } else {
                list.add(file.getAbsolutePath());
            }
        }
        return list;
    }

    /**
     * 从文件路径中获取文件名
     * @param filepath
     * @return
     */
    public String getFileName (String filepath) {
        filepath = filepath.trim();

        String[] temp = filepath.split("/"); /**split里面必须是正则表达式，"\\"的作用是对字符串转义*/

        String fileName = temp[temp.length-1];

//        System.out.println("fileName = " + fileName);

        return fileName;
    }

    /**
     * 删除文件
     * @param filePathAndName 指定得路径
     */
    public boolean delFile(String filePathAndName) {
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            java.io.File myDelFile = new java.io.File(filePath);
            myDelFile.delete();
        } catch (Exception e) {
            return false;
        }

        return true;
    }
}